package dao

import (
	"ProductServer/dao/db"
	"ProductServer/model"
	"log"
)

//InsertProduct ..向数据库插入商品
func InsertProduct(pro *model.Product) uint32 {
	res, err := db.Stmt[db.InsertProduct].Exec(pro.ProductName, pro.ProductNum, pro.ProductImage, pro.ProductURL)
	if err != nil {
		log.Printf(err.Error())
		return 0
	}
	id, err := res.LastInsertId()
	if err != nil {
		log.Printf(err.Error())
	}
	return uint32(id)
}

//XSelectProduct ..sqlx从数据库查询一个商品的信息
func XSelectProduct(pid uint32) (pro *model.Product) {
	pro = &model.Product{}
	sqlstr := "select productName,productNum,productImage,productUrl from product where ID = ?"
	err := db.DB.Get(pro, sqlstr, pid)
	if err != nil {
		log.Printf(err.Error())
		return nil
	}
	return
}

//SelectProduct ..从数据库查询一个商品的信息
func SelectProduct(pid uint32) (pro *model.Product) {
	pro = &model.Product{ID: pid}
	err := db.Stmt[db.SelectProduct].QueryRow(pid).Scan(&pro.ProductName, &pro.ProductNum, &pro.ProductImage, &pro.ProductURL)
	if err != nil {
		log.Printf(err.Error())
		return nil
	}
	return
}

//DeleteProduct ..删除一个商品信息
func DeleteProduct(pid uint32) bool {
	_, err := db.Stmt[db.DeleteProduct].Exec(pid)
	if err != nil {
		log.Printf(err.Error())
		return false
	}
	return true
}

//UpdateProduct ..修改商品信息
func UpdateProduct(pro *model.Product) bool {
	res, err := db.Stmt[db.UpdateProduct].Exec(pro.ProductName, pro.ProductNum, pro.ProductImage, pro.ProductURL, pro.ID)
	if err != nil {
		log.Printf(err.Error())
		return false
	}
	if conut, _ := res.RowsAffected(); conut == 0 {
		return false
	}
	return true
}

//SelectProducts ..获取一定数量的商品 id>pid 获取个数<=conut
func SelectProducts(pid, conut uint32) (products []*model.Product) {
	rows, err := db.Stmt[db.SelectProducts].Query(pid, conut)
	if err != nil {
		log.Printf(err.Error())
		return nil
	}
	defer rows.Close()
	for rows.Next() {
		product := &model.Product{}
		err = rows.Scan(&product.ID, &product.ProductName, &product.ProductNum, &product.ProductImage, &product.ProductURL)
		if err != nil {
			log.Printf(err.Error())
			continue
		}
		products = append(products, product)
	}
	return
}
